package deliciouse.dao.impl;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import deliciouse.dao.DaoException;
import deliciouse.dao.UserDao;
import deliciouse.entity.Food;
import deliciouse.entity.Users;

public class UserDaoImpl implements UserDao {
	private static class UsersRowMapper implements RowMapper<Users> {
		public Users mapRow(ResultSet rs) throws SQLException {
			Users u = new Users();
			u.setPassword(rs.getString("password"));
			u.setAdmin(rs.getString("isadmin"));
			u.setUserName(rs.getString("userName"));
			return u;
		}
	}
	
	private JdbcTemplate db = new JdbcTemplate();

	@Override
	public boolean userCheckIn(Users users) {
		ArrayList parameters = new ArrayList();
		String sql = "select * from users where  username=? and `password` =?";
		parameters.add(users.getUserName());
		parameters.add(users.getPassword());
		
		return db.check(sql, parameters.toArray());

	}

	@Override
	public boolean addUser(Users user) {
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			//db.openConnection();
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/delicious", "root", "");
			stmt = conn.prepareStatement("insert into users(userName,password,LastLoginTime) values(?,?,?)");
			stmt.setString(1, user.getUserName());
			stmt.setString(2, user.getPassword());
			stmt.setDate(3, user.getLastLoginTime());
			stmt.executeUpdate();
			return true;
		} catch (Exception ex) {
			throw new DaoException();
		} finally {
			db.closeResx(rs, stmt, conn);
		}


	}

	@Override
	public boolean userIsExist(String username) {
		String sql="select * from users where username =?";
		
		return db.check(sql, username);
	}

	@Override
	public Users fetchisAdmin(String username) {
		String sql="select * from users where username=?";
		return  db.query(sql, new UsersRowMapper(),username);
	}
}
